<?php

namespace app\common\model;

use app\common\func\Lib;
use think\Model;


class Company extends Model
{

    

    

    // 表名
    protected $name = 'company';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = "create_time";
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'create_time_text',
        'product_text'
    ];
    

    public function getProductTextAttr($value, $data){
        $str = "";
        $arr = explode(",",$data['product_ids']);
        if(count($arr) > 0){
            foreach ($arr as $val){
                $product = Lib::getProductById($val);
                if($product){
                    $str .= "【".$product->name."】";
                }else{
                    $str = "【暂未设置】";
                }
            }
        }else{
            $str = "【暂未设置】";
        }
        return $str;
    }
    
    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function level()
    {
        return $this->belongsTo('app\common\model\CompanyLevel', 'level_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function product()
    {
        return $this->belongsTo('app\common\model\Product', 'product_ids', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
